import pandas as pda
from numpy import *
import operator
import time
from sklearn import datasets
from sklearn.model_selection import train_test_split

def prepare_data(file_path, test_size, random_state):
    data = pda.read_csv(file_path)
    x = data.iloc[:,0:4].as_matrix()
    y = data.iloc[:,4:5].as_matrix()
    return train_test_split(x, y, test_size = test_size, random_state = random_state)

def knn(k, test_data, train_data, labels):
    train_data_size = train_data.shape[0]
    test_data_t = tile(test_data, (train_data_size, 1))
    diff = train_data - test_data_t
    diff_sqr = diff**2
    diff_sqr_sum = diff_sqr.sum(axis = 1)
    distance = diff_sqr_sum**0.5
    distance_sort = distance.argsort()
    label_count = {}
    for i in range(0, k):
        this_label = labels[distance_sort[i]]
        label_count[this_label] = label_count.get(this_label, 0) + 1
    count_sort = sorted(label_count, key = lambda x:label_count[x], reverse = True)
    return count_sort[0]

def run_knn(file,test_s,ran_s):
    begin_time = time.time()
    x_train, x_test, y_train, y_test = prepare_data(file, test_s, ran_s)
    test_row_size = x_test.shape[0]
    print("File path: " + file)
    print("Test row size: " + str(test_row_size))
    print("Test size: " + str(test_s))
    print("Random state: " + str(ran_s))
    test_predict = []
    for i in range(0,test_row_size):
        rst_label = knn(3, x_test[i], x_train, y_train.reshape(-1).tolist())
        test_predict.append(rst_label)
    y_test_c = y_test.reshape(-1).tolist()
    compare_rst = array(test_predict) == array(y_test_c)
    ratio = sum(compare_rst)/len(compare_rst)
    end_time = time.time()
    print("Correct Ratio %: " + str(ratio * 100) + "%")
    print("Elapsed Time: " + str((end_time - begin_time) * 1000) + " milliseconds")

file = "./iris.csv"          
test_s = 0.3
ran_s = 40
run_knn(file, test_s, ran_s)
